package com.mustafaiev.tair.cts.dao.jpa;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.mustafaiev.tair.cts.dao.IGroupDAO;
import com.mustafaiev.tair.cts.exeption.DataNotRemovedException;
import com.mustafaiev.tair.cts.exeption.DataNotRetrievedException;
import com.mustafaiev.tair.cts.exeption.DataNotStoredException;
import com.mustafaiev.tair.cts.model.Group;

@Repository(value = "groupDao")
@Transactional
public class GroupDAO implements IGroupDAO {

	private static final Logger LOGGER = Logger.getLogger(GroupDAO.class);

	private static final String RETRIEVE_GROUP_BY_ID = "from Group where id = ?";

	private HibernateTemplate hibernateTemplate;

	@Autowired
	public void setHibernateTemplate(final HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	@Override
	public void doSave(final Group t) throws DataNotStoredException {
		final Session session = this.hibernateTemplate.getSessionFactory()
				.openSession();
		final Transaction transaction = session.getTransaction();
		try {
			transaction.begin();
			session.save(t);
			transaction.commit();
		} catch (final HibernateException e) {
			LOGGER.error(e);
		}

	}

	@Override
	public void doUpdate(final Group t) throws DataNotStoredException {
		final Session session = this.hibernateTemplate.getSessionFactory()
				.openSession();
		final Transaction transaction = session.getTransaction();
		try {
			transaction.begin();
			session.refresh(t);
			transaction.commit();
		} catch (final HibernateException e) {
			LOGGER.error(e);
		}

	}

	@Override
	public Group retrieveGroup(final Long id) throws DataNotRetrievedException {
		final Session session = this.hibernateTemplate.getSessionFactory()
				.openSession();
		final Query query = session.createQuery(RETRIEVE_GROUP_BY_ID);
		query.setLong(0, id);
		final Group group = (Group) query.uniqueResult();
		return group;
	}

	@Override
	public void doDelete(final Group t) throws DataNotRemovedException {
		final Session session = this.hibernateTemplate.getSessionFactory()
				.openSession();
		final Transaction transaction = session.getTransaction();
		try {
			transaction.begin();
			session.delete(t);
			transaction.commit();
		} catch (final HibernateException e) {
			LOGGER.error(e);
		}

	}

	@Override
	public void doDeleteById(final Long id) throws DataNotRemovedException {

	}

}
